<template>
  <div>
    <form-create
        v-model="fApi"
        :rule="rule"
        :option="option"
        style="margin: 30px;"
    ></form-create>

    <el-button type="primary" @click="handleStartProc" style="margin-left: 200px;">
      提交申请
    </el-button>

  </div>
</template>

<script>
  import formCreate from "@form-create/element-ui";
  import {queryStartFormKey, startProc, selectFormById} from './api/dynamicApi'
  import request from "@/utils/request";

  export default {
    name:'TmptDynamicFormStart',
    props:{
      param: {
        type: Object,
        default: ()=>{}
      },
    },
    data () {
      return {
        fApi: null,
        rule:[],
        option:{},
        procDefKey: "wf-2201162032-7629",
        form:{},
        dynamicFormId:'',
      }
    },
    async mounted() {
      await this.initUI();
      await this.initFormSheet();
    },
    methods: {
      async initUI() {
        const result = await queryStartFormKey({"procDefKey":this.procDefKey});
        this.dynamicFormId = result.remark
        console.log(this.dynamicFormId)
      },
      // start a process
      handleStartProc() {
        const data = this.fApi.form
        console.log(data)
        this.fApi.validate((valid, fail)=>{
          if (!valid) {
            return
          }
          const procDef = {}
          procDef.key = this.procDefKey
          procDef.name = "data.procDefName"
          //procDef.userId = "262"
          procDef.formKey = this.dynamicFormId;
          procDef.formData = JSON.stringify(this.fApi.form)
          startProc(procDef).then(r => {
            this.notify(r)
          })
        })
      },
      // 通过 dynamicFormId 自动加载新的表单页面
      async initFormSheet() {
        console.log('dynamicFormId')
        console.log(this.dynamicFormId)
        const result = await selectFormById({"id":this.dynamicFormId})
        if (!result.success) {
          this.notify(result)
          return
        }
        this.rule =  formCreate.parseJson(result.obj.rule)
        this.option = formCreate.parseJson(result.obj.option)

        // 等页面渲染显示出来后，加载数据内容
        console.log('自动加载参数this.param')
        console.log(this.param)
        this.$nextTick(()=>{
          const fields = this.fApi.fields()
          console.log(fields)
          fields.forEach(fieldId=>{
            // 找组件 loadDataAuto，并调用其 loadData(), 完成数据加载
            const vm = this.fApi.el(fieldId)
            const formCreateInject = vm.formCreateInject
            if (formCreateInject && formCreateInject.prop.type==='loadDataAuto') {
              vm.loadData(this.param)
            }

          })
        })
      },
      getFApi() {
        return this.fApi
      },
      getElVm(fieldId) {
        const vm = this.fApi.el(fieldId)
        return vm
      },
    }
  }
</script>
